<template>
  <div ref="containerRef" v-show="props.showEditor"></div>
</template>

<script setup lang="ts">
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { onUnmounted } from '@vue/runtime-core'
import { KEY_CONSTANTS } from '@/cache'

//markdown格式
const markdown = defineModel({ type: String, default: '' })
const containerRef = ref()
declare type PropType = {
  //当填入元素自身的 HTMLElement 时需设置 options.cache.id 或将 options.cache.enable 设置为 false，为了避免麻烦，统一只能设置id字符串
  id: string
  //挂载到指定元素，编辑器渲染比较慢，所以可以在列表页渲染完毕后隐藏起来，然后再显示到指定的元素下
  //或者页面使用loading，渲染完毕后关闭loading
  el?: HTMLElement
  showEditor?: boolean
  //初始时使用，后续不应该再修改
  options?: IOptions
}

const props = withDefaults(defineProps<PropType>(), {
  showEditor: true
})
const vditor = ref<Vditor>()
watch(
  () => props.showEditor,
  (value) => {
    if (value) {
      if (props.el) {
        props.el.insertBefore(containerRef.value.children[0], null)
      }
    } else {
      if (props.el) {
        containerRef.value.insertBefore(props.el.childNodes[0], null)
      }
    }
  }
)
onMounted(() => {
  const div = document.createElement('div')
  div.id = `${KEY_CONSTANTS.BASE_KEY}-${props.id}`
  containerRef.value.insertBefore(div, null)
  vditor.value = new Vditor(`${KEY_CONSTANTS.BASE_KEY}-${props.id}`, {
    ...props.options,
    after() {
      //设置初始值
      vditor.value?.setValue(markdown.value)
      props.options?.after?.()
    },
    input(value) {
      markdown.value = value
      props.options?.input?.(value)
    }
  })
})
onUnmounted(() => {
  vditor.value?.destroy()
})
</script>
<style scoped lang="scss"></style>
